package com.castle.fortress.admin.cms.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.cms.dto.CmsChannelDto;
import com.castle.fortress.admin.cms.dto.CmsColConfigDto;
import com.castle.fortress.admin.cms.entity.CmsChannelEntity;
import com.castle.fortress.admin.cms.service.CmsChannelAuditService;
import com.castle.fortress.admin.cms.service.CmsChannelService;
import com.castle.fortress.admin.cms.service.CmsColConfigService;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.system.entity.SysRole;
import com.castle.fortress.admin.system.entity.SysUser;
import com.castle.fortress.admin.utils.ExcelUtils;
import com.castle.fortress.admin.utils.WebUtil;
import com.castle.fortress.common.entity.DynamicExcelEntity;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.BizErrorCode;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.utils.CommonUtil;
import com.castle.fortress.common.utils.ConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * cms栏目/导航菜单配置表 控制器
 *
 * @author castle
 * @since 2022-03-09
 */
@Api(tags="cms栏目/导航菜单配置表管理控制器")
@Controller
public class CmsChannelController {
    @Autowired
    private CmsChannelService cmsChannelService;
    @Autowired
    private CmsColConfigService cmsColConfigService;
    @Autowired
    private CmsChannelAuditService cmsChannelAuditService;

	/**
	 * cms栏目/导航菜单配置表的分页展示
	 * @param cmsChannelDto cms栏目/导航菜单配置表实体类
	 * @param current 当前页
	 * @param size  每页记录数
	 * @return
	 */
	@ApiOperation("cms栏目/导航菜单配置表分页展示")
	@GetMapping("/cms/cmsChannel/page")
	@ResponseBody
	@RequiresPermissions("cms:cmsChannel:pageList")
	public RespBody<IPage<CmsChannelDto>> pageCmsChannel(CmsChannelDto cmsChannelDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
		Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
		Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
		Page<CmsChannelDto> page = new Page(pageIndex, pageSize);
			IPage<CmsChannelDto> pages = cmsChannelService.pageCmsChannel(page, cmsChannelDto);

		return RespBody.data(pages);
	}

    /**
     * cms栏目/导航菜单配置表的树形展示
     * @param cmsChannelDto cms栏目/导航菜单配置表实体类
     * @return
     */
    @ApiOperation("cms栏目/导航菜单配置表分页展示")
    @GetMapping("/cms/cmsChannel/tree")
    @ResponseBody
    public RespBody<List<CmsChannelDto>> treeCmsChannel(CmsChannelDto cmsChannelDto){
	    List<CmsChannelDto> list = cmsChannelService.listCmsChannel(cmsChannelDto);
	    //展示时需要展示到顶级
	    Set<Long> ids=new HashSet<>();
	    for(CmsChannelDto s:list){
		    ids.add(s.getId());
	    }
	    List<Long> parentId =new ArrayList<>();
	    List<CmsChannelDto> parentList=new ArrayList<>();
	    for(CmsChannelDto s:list){
		    if(s.getParentId()!=null&&!ids.contains(s.getParentId())){
			    parentId.add(s.getParentId());
		    }
	    }
	    if(!parentId.isEmpty()){
		    QueryWrapper<CmsChannelEntity> wrapper=new QueryWrapper<>();
		    wrapper.in("id",parentId);
		    parentList= ConvertUtil.transformObjList(cmsChannelService.list(wrapper),CmsChannelDto.class);
		    list.addAll(parentList);
	    }
	    do{
		    parentId =new ArrayList<>();
		    for(CmsChannelDto s:parentList){
			    if(s.getParentId()!=null){
				    parentId.add(s.getParentId());
			    }
		    }
		    if(!parentId.isEmpty()){
			    QueryWrapper<CmsChannelEntity> wrapper=new QueryWrapper<>();
			    wrapper.in("id",parentId);
			    parentList= ConvertUtil.transformObjList(cmsChannelService.list(wrapper),CmsChannelDto.class);
			    list.addAll(parentList);
		    }
	    }while(!parentId.isEmpty());
	    return RespBody.data(ConvertUtil.listToTree(list));
    }

    /**
     * cms栏目/导航菜单配置表的权限树形展示
     * @return
     */
    @ApiOperation("cms栏目/导航菜单配置表权限树形展示")
    @GetMapping("/cms/cmsChannel/authTree")
    @ResponseBody
    public RespBody<List<CmsChannelDto>> authTreeCmsChannel(){
        SysUser user = WebUtil.currentUser();
        if(user==null){
            return RespBody.data(new ArrayList<>());
        }
        //管理员和超管查看所有数据
        if(user.getIsAdmin()||user.getIsSuperAdmin()){
            return RespBody.data(ConvertUtil.listToTree(cmsChannelService.listCmsChannel(null)));
        }
        //非管理员用户只能查看授权的栏目及子集栏目
        List<SysRole> roles = user.getRoles();
        List<Long> roldIds= new ArrayList<>();
        for(SysRole r:roles){
            roldIds.add(r.getId());
        }
        if(roldIds.isEmpty()){
            return RespBody.data(new ArrayList<>());
        }
        return RespBody.data(cmsChannelService.authTreeCmsChannel(roldIds));
    }

    /**
     * cms栏目/导航菜单配置表的权限树形展示
     * @return
     */
    @ApiOperation("cms栏目/导航菜单配置表权限树形展示")
    @GetMapping("/cms/cmsChannel/authInfo")
    @ResponseBody
    @RequiresPermissions("cms:cmsRoleChannel:authInfo")
    public RespBody<Map<String,Object>> authInfoCmsChannel(@RequestParam Long roleId){
        Map<String,Object> map = new HashMap<>();
        if(CommonUtil.verifyParamNull(roleId)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        SysUser user = WebUtil.currentUser();
        if(user==null){
            throw new BizException(GlobalRespCode.NO_LOGIN_ERROR);
        }
        List<CmsChannelDto> all = new ArrayList<>();
        //管理员和超管查看所有数据
        if(user.getIsAdmin()||user.getIsSuperAdmin()){
            all = ConvertUtil.listToTree(cmsChannelService.listCmsChannel(null));
        }else{
            //非管理员用户只能查看授权的栏目及子集栏目
            List<SysRole> roles = user.getRoles();
            List<Long> roldIds= new ArrayList<>();
            for(SysRole r:roles){
                roldIds.add(r.getId());
            }
            if(roldIds.isEmpty()){
                throw new BizException(GlobalRespCode.PARAM_MISSED);
            }
            all = cmsChannelService.authTreeCmsChannel(roldIds);
        }
        map.put("allData",all);
        List<Long> roldIds= new ArrayList<>();
        roldIds.add(roleId);
        map.put("checkedData",cmsChannelService.authListCmsChannel(roldIds));
        return RespBody.data(map);
    }

    /**
     * cms栏目/导航菜单配置表的列表展示
     * @param cmsChannelDto cms栏目/导航菜单配置表实体类
     * @return
     */
    @ApiOperation("cms栏目/导航菜单配置表列表展示")
    @GetMapping("/cms/cmsChannel/list")
    @ResponseBody
    public RespBody<List<CmsChannelDto>> listCmsChannel(CmsChannelDto cmsChannelDto){
        List<CmsChannelDto> list = cmsChannelService.listCmsChannel(cmsChannelDto);
        return RespBody.data(list);
    }

    /**
     * cms栏目/导航菜单配置表保存
     * @param cmsChannelDto cms栏目/导航菜单配置表实体类
     * @return
     */
    @ApiOperation("cms栏目/导航菜单配置表保存")
    @PostMapping("/cms/cmsChannel/save")
    @ResponseBody
    @RequiresPermissions("cms:cmsChannel:save")
    public RespBody<String> saveCmsChannel(@RequestBody CmsChannelDto cmsChannelDto){
        if(cmsChannelDto == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
	    RespBody checkResult = cmsChannelService.checkColumnRepeat(cmsChannelDto);
	    if(!checkResult.isSuccess()){
		    return checkResult;
	    }
        cmsChannelDto.setUrl("/page/"+cmsChannelDto.getCode());
        CmsChannelEntity cmsChannelEntity = ConvertUtil.transformObj(cmsChannelDto,CmsChannelEntity.class);
	    if(cmsChannelEntity.getParentId()!=null){
            CmsChannelEntity parent = cmsChannelService.getById(cmsChannelEntity.getParentId());
		    if(StrUtil.isEmpty(parent.getParents())){
                cmsChannelEntity.setParents(parent.getId()+"");
		    }else{
                cmsChannelEntity.setParents(parent.getParents()+","+parent.getId());
		    }
	    }
        if(cmsChannelService.save(cmsChannelEntity)){
            cmsChannelService.auditChild(cmsChannelDto,null);
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * cms栏目/导航菜单配置表编辑
     * @param cmsChannelDto cms栏目/导航菜单配置表实体类
     * @return
     */
    @ApiOperation("cms栏目/导航菜单配置表编辑")
    @PostMapping("/cms/cmsChannel/edit")
    @ResponseBody
    @RequiresPermissions("cms:cmsChannel:edit")
    public RespBody<String> updateCmsChannel(@RequestBody CmsChannelDto cmsChannelDto){
        if(cmsChannelDto == null || cmsChannelDto.getId() == null || cmsChannelDto.getId().equals(0L)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
	    RespBody checkResult = cmsChannelService.checkColumnRepeat(cmsChannelDto);
	    if(!checkResult.isSuccess()){
		    return checkResult;
	    }
        cmsChannelDto.setUrl("/page/"+cmsChannelDto.getCode());
        CmsChannelEntity cmsChannelEntity = ConvertUtil.transformObj(cmsChannelDto,CmsChannelEntity.class);
	    if(cmsChannelEntity.getParentId()!=null){
	    	//校验父级是否是子集
            QueryWrapper<CmsChannelEntity> wrapper=new QueryWrapper<>();
            wrapper.like("parents",cmsChannelEntity.getId());
			wrapper.eq("id",cmsChannelEntity.getParentId());
            List<CmsChannelEntity> sons = cmsChannelService.list(wrapper);
            if(sons!=null && sons.size()>0){
	            throw new BizException(BizErrorCode.PARENT_IS_SON_ERROR);
            }
            CmsChannelEntity parent = cmsChannelService.getById(cmsChannelEntity.getParentId());
		    if(StrUtil.isEmpty(parent.getParents())){
                cmsChannelEntity.setParents(parent.getId()+"");
		    }else{
                cmsChannelEntity.setParents(parent.getParents()+","+parent.getId());
		    }
	    }
        CmsChannelEntity oldEntity = cmsChannelService.getById(cmsChannelEntity.getId());
        if(cmsChannelService.updateById(cmsChannelEntity)){
            cmsChannelService.auditChild(cmsChannelDto,oldEntity);
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * cms栏目/导航菜单配置表删除
     * @param id
     * @return
     */
    @ApiOperation("cms栏目/导航菜单配置表删除")
    @PostMapping("/cms/cmsChannel/delete")
    @ResponseBody
    @RequiresPermissions("cms:cmsChannel:delete")
    public RespBody<String> deleteCmsChannel(@RequestParam Long id){
        if(id == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
	    QueryWrapper<CmsChannelEntity> wrapper=new QueryWrapper<>();
	    wrapper.eq("id",id);
	    wrapper.or().like("parents",id);
	    if(cmsChannelService.remove(wrapper)) {
	        //删除审核人员
            cmsChannelAuditService.removeByChannelId(id);
            return RespBody.data("删除成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }


    /**
     * cms栏目/导航菜单配置表批量删除
     * @param ids
     * @return
     */
    @ApiOperation("cms栏目/导航菜单配置表批量删除")
    @PostMapping("/cms/cmsChannel/deleteBatch")
    @ResponseBody
    @RequiresPermissions("cms:cmsChannel:deleteBatch")
    public RespBody<String> deleteCmsChannelBatch(@RequestBody List<Long> ids){
        if(ids == null || ids.size()<1){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
	    QueryWrapper<CmsChannelEntity> wrapper=new QueryWrapper<>();
	    wrapper.in("id",ids);
	    for(Long d:ids){
		    wrapper.or().like("parents",d);
	    }
	    if(cmsChannelService.remove(wrapper)) {
            cmsChannelAuditService.removeByChannelIds(ids);
            return RespBody.data("删除成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * cms栏目/导航菜单配置表详情
     * @param id cms栏目/导航菜单配置表id
     * @return
     */
    @ApiOperation("cms栏目/导航菜单配置表详情")
    @GetMapping("/cms/cmsChannel/info")
    @ResponseBody
    @RequiresPermissions("cms:cmsChannel:info")
    public RespBody<CmsChannelDto> infoCmsChannel(@RequestParam Long id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        CmsChannelEntity cmsChannelEntity = cmsChannelService.getById(id);
        CmsChannelDto cmsChannelDto = ConvertUtil.transformObj(cmsChannelEntity,CmsChannelDto.class);
        //获取该栏目的审核人员信息
        if(cmsChannelEntity.getAuditflag()){
            List<Map<String,Object>> auditors = cmsChannelAuditService.getAuditorByChannelId(id);
            cmsChannelDto.setAuditUser(auditors);
        }
        return RespBody.data(cmsChannelDto);
    }

    /**
     * 栏目对应模型的扩展字段
     * @param id cms栏目/导航菜单配置表id
     * @return
     */
    @ApiOperation("栏目对应模型的扩展字段")
    @GetMapping("/cms/cmsChannel/cols")
    @ResponseBody
    public RespBody<CmsChannelDto> colCmsChannel(@RequestParam Long id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        CmsChannelEntity cmsChannelEntity = cmsChannelService.getById(id);
        CmsChannelDto cmsChannelDto = ConvertUtil.transformObj(cmsChannelEntity,CmsChannelDto.class);
        List<CmsColConfigDto> list = cmsColConfigService.listByChannel(id);
        cmsChannelDto.setCols(list);
        return RespBody.data(cmsChannelDto);
    }

	/**
     * 动态表头导出 依据展示的字段导出对应报表
     * @param dynamicExcelEntity
     * @param response
     * @throws Exception
     */
	@PostMapping("/cms/cmsChannel/exportDynamic")
	@ApiOperation("动态表头导出，依据展示的字段导出对应报表")
	public void exportDynamic(@RequestBody DynamicExcelEntity<CmsChannelDto> dynamicExcelEntity, HttpServletResponse response) throws Exception {
		List<CmsChannelDto> list = cmsChannelService.listCmsChannel(dynamicExcelEntity.getDto());
		//字典、枚举、接口、json常量等转义后的列表数据 根据实际情况初始化该对象，null为list数据直接导出
		List<List<Object>> dataList = null;
		/**
        * 根据实际情况初始化dataList,可参照 com.castle.fortress.admin.system.controller.TmpDemoController类中方法：exportDynamic
        */
		ExcelUtils.exportDynamic(response,dynamicExcelEntity.getFileName()+".xlsx",null,list,dynamicExcelEntity.getHeaderList(),dataList);
	}


}
